package com.jd.jdoss.web;

import com.alibaba.fastjson.JSON;
import com.jd.jdoss.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@RestController
public class FileController {

    @Resource
    private FileService fileService;
    /**
     * 文件上传
     * @param files
     * @param filePath
     * @return
     */
    @PostMapping("saveFiles")
    public String save(@RequestParam(value = "files",required = false) MultipartFile[] files,String filePath) {
        Map<String, Object> returnMap = new HashMap<>();
        if(files == null) {
            log.warn("Client no upload files");
            returnMap.put("status", 1);
        }else {
            String[] fileNames =  Arrays.stream(files).map(file -> fileService.saveFile(file,filePath)).toArray(String[]::new);
            returnMap.put("status", 0);
            returnMap.put("files", fileNames);
        }
        return JSON.toJSONString(returnMap);
    }

    /**
     * 文件下载
     * @param filePath
     * @return
     */
    @GetMapping("downFile")
    public String down(String filePath) {
        return "";
    }

    /**
     * 单个文件上传
     * @param file
     * @param filePath
     * @return
     */
    @PostMapping("singleSave")
    public String singleSave(@RequestParam(value = "file",required = false) MultipartFile file,String filePath) {
        Map<String, Object> returnMap = new HashMap<>();
        if(file == null) {
            log.warn("Client no upload files");
            returnMap.put("status", 1);
        }else {
            returnMap.put("status", 0);
            returnMap.put("file",fileService.saveFile(file,filePath));
        }
        return JSON.toJSONString(returnMap);
    }

    /**
     * 删除文件
     * @param filePath
     * @return
     */
    @PostMapping("dropFile")
    public  String dropFile(String filePath) {
        Map<String,Object> returnMap = new HashMap<>();
        String returnStr = fileService.dropFile(filePath);
        log.info(returnStr+"and dropfile:"+filePath);
        if("successful operation".equals(returnStr)) {
            returnMap.put("status", 0);
        }else {
            returnMap.put("status", 1);
        }
        return JSON.toJSONString(returnMap);
    }

}
